/**
 * DownloadItem
 */

 import Validator from "../../../../../utils/validator/Validator";
 import React,{Component}from "react";
 
 class DownloadItem extends Component{
    constructor(props) {
        super(props);
        this.state = {             
            iphone_url: "",
            android_url: ""
        };
    }
    componentWillMount(){
        const {data} = this.props;
        this.iphone_url = data.action.iphone_url || "";
        this.android_url = data.action.android_url || "";
        this.setState({
            iphone_url: this.iphone_url,
            android_url: this.android_url
        });
    }
    checkValidate(){
        let validator = Validator();

        validator.addRule($(this.refs.ios), [{
            validator: "empty",
            error: "ios下载地址不能为空！"
        }, {
            validator: "url",
            error: "ios下载地址格式有误！"
        }]);

        validator.addRule($(this.refs.android), [{
            validator: "empty",
            error: "android下载地址不能为空！"
        }, {
            validator: "url",
            error: "android下载地址格式有误！"
        }]);

        let errors = validator.execute();
        if (errors){
            alert(errors);
            return false;
        }
        return true;
    }
    handleOnChangeUrl(e){
        let element = $(e.target || e.srcElement);
        let value = element.val();
        let type = element.attr("name");

        if (type == "ios"){
            this.iphone_url = value;
        } else if(type == "android") {
            this.android_url = value;
        }
        this.setState({
            iphone_url: this.iphone_url,
            android_url: this.android_url
        });
    }
    saveUrl(){
        if (this.checkValidate()){
            const {data: widget,updateWidget,setState} = this.props;
            widget.action.iphone_url = this.iphone_url;
            widget.action.android_url = this.android_url;
            
            setState({selectedWidget: widget});
            updateWidget(widget);
        }
    }
    render(){
        const {data} = this.props;
        return (
            <div>
                <div className="download-item">
                    <span>IOS</span>
                    <input disabled={data.readOnly} onBlur={() => this.saveUrl()} onChange={(e) => this.handleOnChangeUrl(e)} ref="ios" type="text" name="ios" value={ this.state.iphone_url } />
                </div>
                <div className="download-item">
                    <span>安卓</span>
                    <input disabled={data.readOnly} onBlur={() => this.saveUrl()} onChange={(e) => this.handleOnChangeUrl(e)} ref="android" type="text" name="android" value={ this.state.android_url } />
                </div>
            </div>
        )
    }
 }

 module.exports = DownloadItem;
